package com.example.ytyproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ytyproject.config.SecurityUtil;
import com.example.ytyproject.config.exception.AppException;
import com.example.ytyproject.entity.Role;
import com.example.ytyproject.entity.RoleMenu;
import com.example.ytyproject.entity.User;
import com.example.ytyproject.entity.UserRole;
import com.example.ytyproject.entity.vo.PermissionAllocationVo;
import com.example.ytyproject.entity.vo.R;
import com.example.ytyproject.mapper.RoleMapper;
import com.example.ytyproject.mapper.RoleMenuMapper;
import com.example.ytyproject.mapper.UserRoleMapper;
import com.example.ytyproject.service.RoleMenuService;
import com.example.ytyproject.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yg
 * @since 2023-10-27
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMenuService roleMenuService;

    @Override
    public R listByPage(Role param) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<Role>();
        LambdaQueryWrapper<Role> lambda = queryWrapper.lambda();
        lambda.orderByDesc(Role::getCreateDate);
        Page<Role> page = this.page(new Page<>(param.getPageNo(), param.getPageSize()), queryWrapper);
        return R.ok(page.getRecords(), page.getTotal());
    }

    @Override
    public void addData(Role param) {
        if (StringUtils.isEmpty(param.getRoleCode())) {
            throw new AppException("角色编码不能为空！");
        }
        if (StringUtils.isEmpty(param.getRoleName())) {
            throw new AppException("角色名称不能为空！");
        }
        Role role = findByCode(param.getRoleCode());
        if (role != null) {
            throw new AppException("编码已存在！");
        }
        param.setCreateDate(LocalDateTime.now()).setUpdateDate(LocalDateTime.now());
        this.save(param);
    }

    @Override
    public void updateData(Role param) {
        Role role = findByCode(param.getRoleCode());
        if (role == null) {
            param.setUpdateDate(LocalDateTime.now());
            this.updateById(param);
            return;
        }
        if (!role.getId().equals(param.getId())) {
            throw new AppException("编码已存在！");
        }
        param.setUpdateDate(LocalDateTime.now());
        this.updateById(param);
    }

    @Override
    public Role findByCode(String code) {
        Role role = this.getOne(new QueryWrapper<Role>().lambda().eq(Role::getRoleCode, code));
        return role;
    }

    @Override
    public R queryCurrentUserRoles(String userId) {
        // 1 查询所有的角色
        List<Role> list = this.list();
        if (list.size() == 0) {
            return R.ok();
        }
        list.forEach(e -> e.setUserId(userId));
        List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, userId));
        if (userRoles.size() == 0) {
            return R.ok(list);
        }
        for (Role role : list) {
            Optional<UserRole> first = userRoles.stream().filter(e -> e.getRoleId().equals(role.getId())).findFirst();
            if (first.isPresent()) {
                role.setIsEnable(true).setUserId(userId);
            }
        }
        return R.ok(list);
    }

    @Override
    public void permissionAllocation(PermissionAllocationVo allocationVo) {
        String roleId = allocationVo.getRoleId();
        if (StringUtils.isEmpty(roleId)) {
            throw new AppException("角色id不能为空！");
        }
        // 1 先删除所有的权限
        roleMenuService.remove(new QueryWrapper<RoleMenu>().lambda().eq(RoleMenu::getRoleId, roleId));
        // 2 新增权限
        List<RoleMenu> list = new ArrayList<>();
        for (String menuId : allocationVo.getMenuId()) {
            RoleMenu r = new RoleMenu();
            r.setRoleId(roleId).setMenuId(menuId);
            list.add(r);
        }
        roleMenuService.saveBatch(list);
    }
}
